﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;

namespace DataManagement
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool PostThreadMessage(int threadId, int msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        private static readonly int CLOSE_APP = 0x0801;
        private static readonly int ACTIVE_APP = 0x0802;

        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args.Count() != 0)
            {
                Globalspace._currentUserId = e.Args[0];
            }

            ComponentDispatcher.ThreadPreprocessMessage += ComponentDispatcher_ThreadPreprocessMessage;

            //Globalspace._isVisible = true;
            //SwitchToThisWindow(FindWindow(null, "数据管理"), true);

            base.OnStartup(e);

        }

        private void ComponentDispatcher_ThreadPreprocessMessage(ref MSG msg, ref bool handled)
        {
            if (msg.message == CLOSE_APP)
            {
                Current.Shutdown();
            }
            if (msg.message == ACTIVE_APP)
            {
                Globalspace._isVisible = true;
                
                SwitchToThisWindow(FindWindow(null, "数据管理"), true);
            }
        }
    }
}
